package com.microservice.common.context;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 用户上下文 - 使用ThreadLocal存储当前登录用户信息
 * 优雅地在任何地方获取当前用户信息，无需传递HttpServletRequest
 */
public class UserContext {
    
    private static final ThreadLocal<UserInfo> USER_THREAD_LOCAL = new ThreadLocal<>();
    
    /**
     * 设置当前用户信息
     */
    public static void setUser(UserInfo userInfo) {
        USER_THREAD_LOCAL.set(userInfo);
    }
    
    /**
     * 设置当前用户信息（简化方法）
     */
    public static void setUser(Long userId, String username,String nickName) {
        USER_THREAD_LOCAL.set(new UserInfo(userId, username,nickName));
    }
    
    /**
     * 获取当前用户信息
     */
    public static UserInfo getUser() {
        return USER_THREAD_LOCAL.get();
    }
    
    /**
     * 获取当前用户ID
     */
    public static Long getUserId() {
        UserInfo userInfo = USER_THREAD_LOCAL.get();
        return userInfo != null ? userInfo.getUserId() : null;
    }
    
    /**
     * 获取当前用户名
     */
    public static String getUsername() {
        UserInfo userInfo = USER_THREAD_LOCAL.get();
        return userInfo != null ? userInfo.getUsername() : null;
    }

    public static String getNickname() {
        UserInfo userInfo = USER_THREAD_LOCAL.get();
        return userInfo != null ? userInfo.getNickName() : null;
    }
    
    /**
     * 清除当前用户信息（重要：请求结束后必须清除，防止内存泄漏）
     */
    public static void clear() {
        USER_THREAD_LOCAL.remove();
    }
    
    /**
     * 用户信息类
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class UserInfo {
        private Long userId;
        private String username;
        private String nickName;
        private java.util.Set<String> roles;       // 用户角色集合
        private java.util.Set<String> permissions; // 用户权限集合
        
        public UserInfo(Long userId, String username,String nickName) {
            this.userId = userId;
            this.username = username;
            this.nickName = nickName;
            this.roles = new java.util.HashSet<>();
            this.permissions = new java.util.HashSet<>();
        }
    }
}
